﻿using System;
using System.Collections.Generic;
//using System.Linq;
using System.Text;
// add
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
//using System.Diagnostics;
//using System.IO;
//using System.IO.Ports;
using System.Threading;
// add
using FormBaseLib;

namespace FormBase
{
    public static class CCommon
    {
        public static CBase mLastError = new CBase();
        /// <summary>
        /// get serialized xml text for any class marked as [Serializable()]
        /// </summary>
        public static string SerializeToXMLString<T>(T oFrom)
        {
            using (MemoryStream stream1 = new MemoryStream())
            {
                XmlDocument xmlDoc1 = new XmlDocument();
                XmlSerializer serializer1 = new XmlSerializer(typeof(T));
                serializer1.Serialize(stream1, oFrom);
                stream1.Position = 0;
                xmlDoc1.Load(stream1);
                return xmlDoc1.InnerXml;
            }
        }
        public static string SerializeToUTF8String<T>(T obj)
        {
            // todo: test difference to SerializeToXMLString ?
            //MemoryStream stream1 = new MemoryStream();
            using (MemoryStream stream1 = new MemoryStream())
            {
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
                XmlTextWriter xmlTextWriter = new XmlTextWriter(stream1, Encoding.UTF8);

                xmlSerializer.Serialize(xmlTextWriter, obj);
                MemoryStream stream2 = xmlTextWriter.BaseStream as MemoryStream;
                string xmlString = CCommon.ByteArrayToStringUtf8(stream2.ToArray());

                xmlTextWriter.Close();
                return xmlString;
            }
            //stream1.Close();
            //stream1.Dispose();

        }

        public static bool DescrializeFromFile<T>(string sFile, Encoding Encoding1, T oToLoad)
        {
            try
            {
                using (FileStream fstream1 = new FileStream(sFile, FileMode.Open))
                {
                    XmlSerializer xs1 = new XmlSerializer(typeof(T));
                    using (StreamReader sr1 = new StreamReader(fstream1, Encoding1))
                    {
                        oToLoad = (T)xs1.Deserialize(sr1);
                        return true;
                    }
                }
            }
            catch (Exception ex)
            {
                mLastError.SetLastError("ERROR: DescrializeFromFile(). " + ex.Message);
                oToLoad = default(T);
                return false;
            }
        }

        public static bool SerializerToFile<T>(string sFile, Encoding Encoding1, T oToSave)
        {
            mLastError.ClearLastError();
            try
            {
                XmlSerializer xs1 = new XmlSerializer(typeof(T));
                using (FileStream fstream1 = new FileStream(sFile, FileMode.Create))
                {
                    XmlTextWriter xw1 = new XmlTextWriter(fstream1, Encoding1);
                    xs1.Serialize(xw1, oToSave);
                }
                return true;
            }
            catch (Exception ex)
            {
                mLastError.SetLastError("ERROR: SerializerToFile(). " + ex.Message);
                return false;
            }
        }
        /// <summary>
        /// Copy (deep clone copy) any class marked as [Serializable()]
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="oFrom"></param>
        /// <returns></returns>
        public static T CopyDeepFromSerializable<T>(T oFrom)
        {
            using (MemoryStream stream1 = new MemoryStream())
            {
                BinaryFormatter bFormatter1 = new BinaryFormatter();
                bFormatter1.Serialize(stream1, oFrom);
                stream1.Position = 0;
                return (T)bFormatter1.Deserialize(stream1);
            }
        }
        /// <summary>
        /// dump xml content for any class marked as [Serializable()]
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="oFrom"></param>
        /// <returns></returns>
        public static string DumpSerializableToXML<T>(T oFrom)
        {
            using (MemoryStream stream1 = new MemoryStream())
            {
                XmlDocument xmlDoc1 = new XmlDocument();
                XmlSerializer serializer1 = new XmlSerializer(typeof(T));
                serializer1.Serialize(stream1, oFrom);
                stream1.Position = 0;
                xmlDoc1.Load(stream1);
                return xmlDoc1.InnerXml;
            }
        }
        public static T DeserializeFromUTF8String<T>(string xml)
        {
            using (MemoryStream memoryStream = new MemoryStream(StringToByteArrayUtf8(xml)))
            {
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));

                using (StreamReader xmlStreamReader = new StreamReader(memoryStream, Encoding.UTF8))
                {
                    return (T)xmlSerializer.Deserialize(xmlStreamReader);
                }
            }
        }
        public static string ByteArrayToStringUtf8(byte[] value)
        {
            UTF8Encoding encoding = new UTF8Encoding();
            return encoding.GetString(value);
        }

        public static byte[] StringToByteArrayUtf8(string value)
        {
            UTF8Encoding encoding = new UTF8Encoding();
            return encoding.GetBytes(value);
        }
        private static bool IsUTF8Bytes(byte[] data)
        {
            int charByteCounter = 1;
            byte curByte;
            for (int i = 0; i < data.Length; i++)
            {
                curByte = data[i];
                if (charByteCounter == 1)
                {
                    if (curByte >= 0x80)
                    {
                        while (((curByte <<= 1) & 0x80) != 0)
                        {
                            charByteCounter++;
                        }

                        if (charByteCounter == 1 || charByteCounter > 6)
                        {
                            return false;
                        }
                    }
                }
                else
                {
                    if ((curByte & 0xC0) != 0x80)
                    {
                        return false;
                    }
                    charByteCounter--;
                }
            }
            if (charByteCounter > 1)
            {
                throw new Exception("Error byte format");
            }
            return true;
        }
        public static Encoding GetEncoding(FileStream fs)
        {
            byte[] Unicode = new byte[] { 0xFF, 0xFE, 0x41 };
            byte[] UnicodeBIG = new byte[] { 0xFE, 0xFF, 0x00 };
            byte[] UTF8 = new byte[] { 0xEF, 0xBB, 0xBF }; //with BOM
            Encoding reVal = Encoding.Default;

            BinaryReader r = new BinaryReader(fs, System.Text.Encoding.Default);
            int i;
            int.TryParse(fs.Length.ToString(), out i);
            byte[] ss = r.ReadBytes(i);
            if (IsUTF8Bytes(ss) || (ss[0] == 0xEF && ss[1] == 0xBB && ss[2] == 0xBF))
            {
                reVal = Encoding.UTF8;
            }
            else if (ss[0] == 0xFE && ss[1] == 0xFF && ss[2] == 0x00)
            {
                reVal = Encoding.BigEndianUnicode;
            }
            else if (ss[0] == 0xFF && ss[1] == 0xFE && ss[2] == 0x41)
            {
                reVal = Encoding.Unicode;
            }
            r.Close();
            return reVal;

        }
        public static byte[] StringToByteArray(string sInput, Encoding encoding1)
        {
            // CodeHelper
            return encoding1.GetBytes(sInput);
        }

        public static string ByteArrayToString(byte[] baInput, Encoding encoding1)
        {
            // CodeHelper
            return encoding1.GetString(baInput);
        }

        public static Encoding GetEncoding(string FILE_NAME)
        {
            FileStream fs = new FileStream(FILE_NAME, FileMode.Open, FileAccess.Read);
            Encoding r = GetEncoding(fs);
            fs.Close();
            return r;
        }
        private static T DescrializeFromFile2<T>(string sFile, Encoding Encoding1, T oToLoad)
        {
            try
            {

                using (FileStream fstream1 = new FileStream(sFile, FileMode.Open))
                {
                    XmlSerializer xs1 = new XmlSerializer(typeof(T));
                    using (StreamReader sr1 = new StreamReader(fstream1, Encoding1))
                    {
                        return (T)xs1.Deserialize(sr1);
                    }
                }
            }
            catch (Exception ex)
            {
                //mError.SetError(ex, "DescrializeFromFile");
                mLastError.SetLastError("ERROR:" + ex.Message);
                //return null;
                return default(T);
            }
        }
        public static string gGetPhysicalFilename(long lFileno)
        {
            // return mapped file storage path for (file based upload/download file system)
            // Signed 64-bit integer
            // System.Int64
            // –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

            // file system in tree structure: 
            // 1. tree height = 6.
            // 2. 100 children in each node for the performance concern in Windows file system environment.

            // 1   2     3        4           5             6                7
            //     百    萬       百萬        億            百億
            // 1 - 100 - 10,000 - 1,000,000 - 100,000,000 - 10,000,000,000 - 再大的話同一顆硬碟也放不下了!
            //                                             990,000,000,000
            //                                           1,000,000,000,000
            // dividend over divisor = quotient + remainder
            string s1;
            s1 = (100000000000000L + lFileno).ToString();
            string sFilename = s1.Substring(1, 2)
                + "\\" + s1.Substring(3, 2)
                + "\\" + s1.Substring(5, 2)
                + "\\" + s1.Substring(7, 2)
                + "\\" + s1.Substring(9, 2)
                + "\\" + s1.Substring(11, 2)
                + "\\" + lFileno.ToString();
            return sFilename;

        }
        public static void gSleep(Int32 iMilliseconds)
        {
            // code helper
            Thread.Sleep(iMilliseconds);
        }

    }
}
